package com.steakliu.sun.server.netty.initializer;

import com.steakliu.sun.codec.SunDecoder;
import com.steakliu.sun.codec.SunEncoder;
import com.steakliu.sun.common.thread.ServerConcurrentThreadPool;
import com.steakliu.sun.flow.api.FlowControlPostProcessor;
import com.steakliu.sun.invoker.api.Invoker;
import com.steakliu.sun.server.api.ServerConfig;
import com.steakliu.sun.server.api.ServerLocalServiceCaches;
import com.steakliu.sun.server.netty.handler.SunServerHandler;
import com.steakliu.sun.spi.loader.ExtensionLoader;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.AllArgsConstructor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-08  00:19
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class SunServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final Map<String, ServerLocalServiceCaches> localCacheServices;

    private final Invoker invoker;

    private final ServerConfig config;

    private final ServerConcurrentThreadPool serverConcurrentThreadPool;


    public SunServerChannelInitializer(Map<String, ServerLocalServiceCaches> localCacheServices, Invoker invoker,
                                       ServerConfig config, ServerConcurrentThreadPool serverConcurrentThreadPool) {
        this.localCacheServices = localCacheServices;
        this.invoker = invoker;
        this.config = config;
        this.serverConcurrentThreadPool = serverConcurrentThreadPool;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        socketChannel.pipeline()
                .addLast("encoder", new SunEncoder(config.isUseFlowControl(), config.getFlowControlType()))
                .addLast("decoder", new SunDecoder(config.isUseFlowControl(), config.getFlowControlType()))
                .addLast("serverIdleHandler", new IdleStateHandler(0, 0, config.getHeartbeatInterval() * 2L, TimeUnit.MILLISECONDS))
                .addLast("serverHandler", new SunServerHandler(localCacheServices, invoker, config, serverConcurrentThreadPool));
    }
}
